#!/bin/bash

cd `dirname $0`
#BIN_DIR=`pwd`
#cd ..
myPath=`pwd`

echo "启动目录下所有redis"


RUN="${myPath}/run"

echo "检查日志目录是否存在"
LOG="${myPath}/log"

if [ ! -d "$LOG" ]; then
	echo "日志目录不存在，自动创建。$LOG"
	mkdir "$LOG"
fi
echo ""

config_file="redis.conf"

#IP="192.168.31.152"
# 读取系统配置IP地址
IP=`hostname -i`

#if [ ! -n "$1" ] ;then
#	echo "you have not input a word!"
#else
#	echo "the word you input is $1"
#fi

# 是否带ip参数
if [ -n "$1" ] ;then
	IP=$1
fi

msg="IP地址为 $IP ? (yes/no)"
read -p "$msg" ans
while [[ "x"$ans != "xyes" && "x"$ans != "xno" ]] 
do 
	read -p "$msg" ans
done

if [[ $ans == "no" ]]; then
	exit 0
fi

function while_read_LINE(){
	cat "$myPath/template/$config_file" | while read LINE
	do
		LINE=${LINE//IPIPIP/$IP}          # 替换ip
		LINE=${LINE//RUNRUNRUN/$RUN}      # 替换run
		LINE=${LINE//LOGLOGLOG/$LOG}      # 替换log
		LINE=${LINE//PORTPORTPORT/$1}     # 替换port
		echo $LINE >> "$2/$config_file"
	done
}


for file in $myPath/cluster/*
do
    #echo "$file":
    #if test -f "$file"
    #then
    #    #echo "$file" 是文件
    #    continue
    #fi
    if test -d "$file"
    then
        #echo "$file" 是目录
	echo ""
	echo "进入工作目录 $file"
	cd "$file"
	basename=`pwd`
	port=`basename $basename`
	PIDS=`ps -ef|grep redis | grep server | grep $port |awk '{print $2}'`
	if [ -n "$PIDS" ]; then
		echo "进程已经存在,PID=$PIDS"
		continue
	fi
	#echo "redis目录 $basename"
	#echo "删除原有配置文件"
	#rm -rf *
	#echo "根据模板创建配置文件"
	
	#while_read_LINE $port $basename
	echo "启动redis-server"
	redis-server ./redis.conf
	#echo $?
    fi
done

sleep 2

echo ""
echo "查看redis进程"
ps -ef|grep redis |grep server
echo ""
